//
//  LoanDetailsView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/12/15.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import WebKit

@objc protocol LoanDetailsViewDelegate {
    @objc func applyNowAction(model:GenericLoansModel) //立即申请
    @objc func selectLoanType(model:GenericLoansModel) //选择贷款类型
}

class LoanDetailsView: UIView {
    
    fileprivate var loanMonth = "" //贷款月份
    fileprivate var cell : UIView! //选择模块
    
    weak var delegate : LoanDetailsViewDelegate?
    
    fileprivate var model = GenericLoansModel()

    fileprivate let scrollView = UIScrollView()
    fileprivate let bankImageView = UIImageView() //图标
    fileprivate let bankLabel = UILabel() //银行
    fileprivate let millionLabel = UILabel() //万元
    fileprivate let textField = UITextField.init(Width: 5) //输入金额
    fileprivate let unitLabel = UILabel() //金额单位
    fileprivate let redLineView = UIView() //红色线条
    fileprivate let lendersLabel = UILabel() //放款
    fileprivate let mortgageLabel = UILabel() //抵押
    fileprivate let typeLabel = UILabel() //职业
    fileprivate var loanFeeView : LoanFeeView! //贷款费用
    fileprivate let applyButton = UIButton() //立即申请
    fileprivate let productView = ProductDetailsView() //产品详情
    fileprivate let webView = WKWebView() //网页
    fileprivate let grayView = UIView()
    fileprivate var popularLoansView : PopularLoansView! //热门贷款
    
    init(frame:CGRect,model:GenericLoansModel) {
        super.init(frame: frame)
        
        self.model = model
        
        self.addSubview(scrollView)
        
        scrollView.addSubview(bankImageView)
        
        bankLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 18))
        scrollView.addSubview(bankLabel)
        
        unitLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 20))
        scrollView.addSubview(unitLabel)
        
        millionLabel.textColor = UIColor.lightGray
        millionLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        scrollView.addSubview(millionLabel)
        
        if model.money != "0" {
            textField.text = model.money
        }else if model.money_min != "0" {
            textField.text = model.money_min
        }else{
            textField.text = "1"
        }
        textField.keyboardType = .decimalPad
        textField.font = UIFont.boldSystemFont(ofSize: RATIO(maxNum: 20))
        textField.delegate = self
        textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        scrollView.addSubview(textField)
        
        redLineView.backgroundColor = UIColor.red
        scrollView.addSubview(redLineView)
        
        lendersLabel.textColor = UIColor.lenderColor()
        lendersLabel.textAlignment = .center
        lendersLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 14))
        if model.time_advange != "" {
            lendersLabel.layer.borderColor = UIColor.lenderColor().cgColor
            lendersLabel.layer.borderWidth = 1
        }
        scrollView.addSubview(lendersLabel)
        
        mortgageLabel.textColor = UIColor.lenderColor()
        mortgageLabel.textAlignment = .center
        mortgageLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: RATIO(maxNum: 14)))
        scrollView.addSubview(mortgageLabel)
        
        typeLabel.textColor = UIColor.lenderColor()
        typeLabel.textAlignment = .center
        typeLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: RATIO(maxNum: 14)))
        typeLabel.layer.borderWidth = 1
        typeLabel.layer.borderColor = UIColor.lenderColor().cgColor
        scrollView.addSubview(typeLabel)
        
        loanFeeView = LoanFeeView.init(model: model)
        loanFeeView.delegate = self
        scrollView.addSubview(loanFeeView)
        
        applyButton.setTitle(applyNow, for: .normal)
        applyButton.setTitleColor(UIColor.black, for: .normal)
        applyButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        applyButton.backgroundColor = UIColor.applicationColor()
        applyButton.layer.cornerRadius = RATIO_H(maxNum: 20)
        applyButton.layer.masksToBounds = true
        applyButton.addTarget(self, action: #selector(applyNowAction), for: .touchUpInside)
        scrollView.addSubview(applyButton)
        
        scrollView.addSubview(productView)
        
        webView.scrollView.bounces = false
        webView.navigationDelegate = self
        scrollView.addSubview(webView)
        
        //监听webview高度变化
        webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
        
        grayView.backgroundColor = UIColor.mineColor()
        scrollView.addSubview(grayView)
        
        popularLoansView = PopularLoansView.init(bankName: model.organization_name!)
        popularLoansView.delegate = self
        scrollView.addSubview(popularLoansView)
        
        KMTool.setRefresh(with: scrollView, headerAction: {[weak self] in
            self?.popularLoansView.getData()
        }, footerAction: nil)
        
        updateData(model: model)
    }
    
    //MARK: 刷新数据
    fileprivate func updateData(model:GenericLoansModel) {
        
        bankImageView.image = UIImage.imageWithName(KMTool.selectBankImage(bankName: model.organization_name!))
        bankLabel.text = model.organization_name! + "-" + model.product_name!
        unitLabel.text = "¥"
        if model.money != "0" {
            textField.text = model.money
        }else if model.money_min != "0" {
            textField.text = model.money_min
        }else {
            textField.text = "1"
        }
        millionLabel.text = millionYuan
        lendersLabel.text = model.time_advange
        mortgageLabel.text = model.mortgage
        if model.mortgage != "" {
            mortgageLabel.layer.borderColor = UIColor.lenderColor().cgColor
            mortgageLabel.layer.borderWidth = 1
        }
        typeLabel.text = model.identitychoose
        if model.identitychoose == "" {
            typeLabel.text = model.identity
        }
        var htmlString = "<html><head><meta name='viewport' content='initial-scale=1, maximum-scale=1, user-scalable=no'></head><body>\(model.details ?? "")</body></html>"
        if htmlString.contains("<img") {
            htmlString = htmlString.replacingOccurrences(of: "<img", with: "<img width=‘100%’ height='哈哈'")
        }
        webView.loadHTMLString(htmlString, baseURL: URL.init(string: kmHttps))
        
        popularLoansView.getData()
        
        scrollView.snp.remakeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        bankImageView.snp.remakeConstraints { (make) in
            make.top.equalToSuperview().offset(RATIO_H(maxNum: 20))
            make.left.equalTo(self).offset(RATIO(maxNum: 20))
            make.width.height.equalTo(RATIO_H(maxNum: 40))
        }
        
        bankLabel.snp.remakeConstraints { (make) in
            make.left.equalTo(bankImageView.snp.right).offset(RATIO(maxNum: 10))
            make.centerY.equalTo(bankImageView)
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        unitLabel.snp.remakeConstraints { (make) in
            make.top.equalTo(bankImageView.snp.bottom).offset(RATIO_H(maxNum: 30))
            make.left.equalTo(bankImageView)
            make.height.equalTo(RATIO_H(maxNum: 30))
            make.width.equalTo(15)
        }
        
        millionLabel.snp.remakeConstraints { (make) in
            make.centerY.bottom.equalTo(unitLabel)
            make.right.equalTo(self).offset(RATIO(maxNum: -20))
            make.width.equalTo(40)
        }
        
        textField.snp.remakeConstraints { (make) in
            make.left.equalTo(unitLabel.snp.right)
            make.right.equalTo(millionLabel.snp.left)
            make.height.centerY.equalTo(unitLabel)
        }
        
        redLineView.snp.remakeConstraints { (make) in
            make.top.equalTo(textField.snp.bottom).offset(RATIO_H(maxNum: 5))
            make.left.equalTo(unitLabel)
            make.right.equalTo(millionLabel)
            make.height.equalTo(1)
        }
        
        lendersLabel.snp.remakeConstraints { (make) in
            make.top.equalTo(redLineView.snp.bottom).offset(RATIO_H(maxNum: 10))
            make.left.equalTo(redLineView)
            make.height.equalTo(RATIO_H(maxNum: 30))
            make.width.equalTo(model.time_advange != "" ?  (model.time_advange?.size(font: RATIO(maxNum: 14), height: RATIO_H(maxNum: 30)).width)! : 0)
        }
        
        mortgageLabel.snp.remakeConstraints { (make) in
            make.left.equalTo(lendersLabel.snp.right).offset(model.time_advange == "" ? 0 : RATIO(maxNum: 10))
            make.centerY.height.equalTo(lendersLabel)
            make.width.equalTo(model.mortgage != "" ? (model.mortgage?.size(font: RATIO(maxNum: 14), height: RATIO_H(maxNum: 30)).width)! : 0)
        }
        
        
        
        
        typeLabel.snp.remakeConstraints { (make) in
            make.centerY.height.equalTo(mortgageLabel)
            make.left.equalTo(mortgageLabel.snp.right).offset(model.mortgage == "" ? 0 : RATIO(maxNum: 10))
            make.width.equalTo((typeLabel.text?.size(font: RATIO(maxNum: 14), height: RATIO_H(maxNum: 30)).width)!)
        }
        
        self.layoutIfNeeded()
        
        if typeLabel.frame.maxX > ScreenW - RATIO(maxNum: 20) {
            
            typeLabel.snp.remakeConstraints { (make) in
                make.top.equalTo(mortgageLabel.snp.bottom).offset(RATIO_H(maxNum: 10))
                make.left.height.equalTo(lendersLabel)
                make.width.equalTo((typeLabel.text?.size(font: RATIO(maxNum: 14), height: RATIO_H(maxNum: 30)).width)!)
            }
        }
        
        loanFeeView.snp.remakeConstraints { (make) in
            make.top.equalTo(typeLabel.snp.bottom).offset(RATIO_H(maxNum: 10))
            make.left.right.equalTo(redLineView)
            make.height.equalTo(RATIO_H(maxNum: 310))
        }
        
        applyButton.snp.remakeConstraints { (make) in
            make.top.equalTo(loanFeeView.snp.bottom).offset(RATIO_H(maxNum: 30))
            make.centerX.equalToSuperview()
            make.width.equalTo(ScreenW/2)
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
        
        productView.snp.remakeConstraints { (make) in
            make.top.equalTo(applyButton.snp.bottom).offset(RATIO_H(maxNum: 30))
            make.left.right.equalTo(self)
            make.height.equalTo(RATIO_H(maxNum: 50))
        }
        
        webView.snp.remakeConstraints { (make) in
            make.top.equalTo(productView.snp.bottom).offset(RATIO_H(maxNum: 10))
            make.left.right.equalTo(self)
            make.bottom.equalToSuperview()
        }
        
        grayView.snp.remakeConstraints { (make) in
            make.top.equalTo(webView.snp.bottom)
            make.left.right.equalTo(self)
            make.height.equalTo(RATIO_H(maxNum: 10))
        }
        
        popularLoansView.snp.remakeConstraints { (make) in
            make.top.equalTo(grayView.snp.bottom).offset(RATIO_H(maxNum: 10))
            make.left.right.equalTo(self)
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
    }
    
    //MARK: 立即申请
    @objc fileprivate func applyNowAction() {
        
        self.delegate?.applyNowAction(model: self.model)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "contentSize" {
            
            webView.snp.remakeConstraints { (make) in
                make.top.equalTo(self.productView.snp.bottom).offset(RATIO_H(maxNum: 10))
                make.left.right.equalTo(self)
                make.height.equalTo(webView.scrollView.contentSize.height)
            }
            
            self.layoutIfNeeded()
            
            self.scrollView.contentSize = .init(width: ScreenW, height: popularLoansView.frame.maxY + StatusBarAddNavBarHeight)
            
            
        }
    }
    
    //MARK: 输入贷款金额
    @objc fileprivate func textFieldDidChange() {
        
        if textField.text == "." {
            textField.text = ""
            return
        }
        
        if self.cell is LoanFeeCell {
            selectLoanMonth(cell: (self.cell as? LoanFeeCell)!, monthCount: self.loanMonth)
        }else if self.cell is LoanFeeFootView {
            inputLoanMonth(footView: (self.cell as? LoanFeeFootView)!)
        }
        
        
    }
    
    deinit {
        webView.scrollView.removeObserver(self, forKeyPath: "contentSize")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension LoanDetailsView : WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
        
        
    }
}

extension LoanDetailsView : PopularLoansViewDelegate {
    
    //MARK: 修改坐标
    func changeTableViewFrame(count: Int) {
        
        popularLoansView.snp.remakeConstraints { (make) in
            make.top.equalTo(grayView.snp.bottom).offset(RATIO_H(maxNum: 10))
            make.left.right.equalTo(self)
            make.height.equalTo(RATIO_H(maxNum: 140) * CGFloat(count) + RATIO_H(maxNum: 40))
        }
        
        scrollView.mj_header.endRefreshing()
        self.scrollView.contentSize = .init(width: ScreenW, height: webView.frame.maxY + StatusBarAddNavBarHeight)
    }
    
    //MARK: 选择贷款类型
    func selectLoanType(model: GenericLoansModel) {
        
        self.model = model
        updateData(model: model)
        self.delegate?.selectLoanType(model: model)
        
        textFieldDidChange()
    }
}

extension LoanDetailsView : LoanFeeViewDelegate {
    
    //MARK: 选择贷款月份
    func selectLoanMonth(cell: LoanFeeCell,monthCount:String) {
        
        self.cell = cell
        self.loanMonth = monthCount
        
        var money = ""
        if model.money != "0" {
            money = model.money!
        }else if model.money_min != "0" {
            money = model.money_min!
        }
        
        if (Double(textField.text ?? "") ?? 0) > (Double(money) ?? 0) {
            textField.text = money
            KMTool.showText(_text: "贷款金额不能超过\(money)万元")
        }
        
        switch model.rate_unit {
        case "年":
            //总利息
            let loanAmount = (Double(textField.text!) ?? 0) * 10000 * Double(model.interest_rate!)!/12 * 0.01 * Double(monthCount)!
            //月供
            let month = ((Double(textField.text!) ?? 0) * 10000 + loanAmount)/Double(monthCount)!
                
            cell.interestLabel.text = "总利息¥" + "\(String(format: "%.2f", loanAmount))" + "元"
            cell.supplyLabel.text = "月供" + "\(String(format: "%.2f", month))" + "元"
        case "月":
            //总利息
            let loanAmount = (Double(textField.text!) ?? 0) * 10000 * Double(model.interest_rate!)! * 0.01 * Double(monthCount)!
            //月供
            let month = ((Double(textField.text!) ?? 0) * 10000 + loanAmount)/Double(monthCount)!
            
            cell.interestLabel.text = "总利息¥" + "\(String(format: "%.2f", loanAmount))" + "元"
            cell.supplyLabel.text = "月供" + "\(String(format: "%.2f", month))" + "元"
        case "日":
            //总利息
            let loanAmount = (Double(textField.text!) ?? 0) * 10000 * Double(model.interest_rate!)! * 30 * 0.01 * Double(monthCount)!
            //月供
            let month = ((Double(textField.text!) ?? 0) * 10000 + loanAmount)/Double(monthCount)!
            
            cell.interestLabel.text = "总利息¥" + "\(String(format: "%.2f", loanAmount))" + "元"
            cell.supplyLabel.text = "月供" + "\(String(format: "%.2f", month))" + "元"
        default:
            break
        }
    }
    
    //MARK: 输入贷款月份
    func inputLoanMonth(footView: LoanFeeFootView) {
        
        self.cell = footView
        self.loanMonth = footView.monthTextField.text!
        
        if footView.monthTextField.text == "" {
            footView.interestLabel.text = "总利息¥0.00元"
            footView.supplyLabel.text = "月供0.00元"
            return
        }
        
        switch model.rate_unit {
        case "年":
            //总利息
            let loanAmount = (Double(textField.text!) ?? 0)*10000 * Double(model.interest_rate!)!/12*0.01*Double(footView.monthTextField.text!)!
            //月供
            let month = ((Double(textField.text!) ?? 0) * 10000 + loanAmount)/(Double(footView.monthTextField.text!) ?? 0)
            
            footView.interestLabel.text = "总利息¥" + "\(String(format: "%.2f", loanAmount))" + "元"
            footView.supplyLabel.text = "月供" + "\(String(format: "%.2f", month))" + "元"
        case "月":
            //总利息
            let loanAmount = (Double(textField.text!) ?? 0) * 10000 * Double(model.interest_rate!)! * 0.01 * Double(footView.monthTextField.text!)!
            //月供
            let month = ((Double(textField.text!) ?? 0) * 10000 + loanAmount)/(Double(footView.monthTextField.text!) ?? 0)
            
            footView.interestLabel.text = "总利息¥" + "\(String(format: "%.2f", loanAmount))" + "元"
            footView.supplyLabel.text = "月供" + "\(String(format: "%.2f", month))" + "元"
        case "日":
            //总利息
            let loanAmount = (Double(textField.text!) ?? 0) * 10000*Double(model.interest_rate!)! * 30*0.01*Double(footView.monthTextField.text!)!
            //月供
            let month = ((Double(textField.text!) ?? 0) * 10000 + loanAmount)/(Double(footView.monthTextField.text!) ?? 0)
            
            footView.interestLabel.text = "总利息¥" + "\(String(format: "%.2f", loanAmount))" + "元"
            footView.supplyLabel.text = "月供" + "\(String(format: "%.2f", month))" + "元"
        default:
            break
        }
    }
}

extension LoanDetailsView : UITextFieldDelegate {
    
    //MARK: 输入限制
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if textField.text == "0" {
            if range.length == 1 && string.count == 0 {
                return true
            }else{
                if string == "." {
                    return true
                }else{
                   return false
                }
            }
        }
        
        if textField.text == "0." {
            if range.length == 1 && string.count == 0 {
                return true
            }else{
                if string == "." {
                    return false
                }else{
                    return true
                }
            }
        }
        
        return true
    }
}
